﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;

namespace PMAF.K3Cloud.SCM.DynamicForm.BusinessPlugIn
{
    [HotUpdate]
    [Description("应收收款核销记录应收计息")]
    public class ARMatchRecRecord : AbstractDynamicFormPlugIn
    {
        private readonly string receivableType = "180ecd4afd5d44b5be78a6efe4a7e041";
        private readonly string receiveReturnType = "ef06f87d394a462d9f96cb2397803372";
        private readonly string costReceivableType = "00505694799c955111e325bc9e6eb056";
        private readonly decimal interestRate = 0.00011M;
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            switch (e.BarItemKey.ToUpperInvariant())
            {
                //PMAF_tbInterest
                case "PMAF_TBINTEREST":
                    Entity entity = View.BillBusinessInfo.GetEntity("FRecordEntry");
                    //转换成行
                    DynamicObjectCollection rows = View.Model.GetEntityDataObject(entity);
                    //定义选择行数据
                    DynamicObjectCollection selectedRows = new DynamicObjectCollection();
                    int selectedAcount = 0;
                    foreach(DynamicObject row in rows)
                    {
                        string sourceType = row["FSOURCETYPE"].ToString();
                        if (Convert.ToBoolean(row["FSelect"]) 
                            && (sourceType == receivableType 
                            || sourceType == receiveReturnType
                            || sourceType == costReceivableType))
                        {
                            selectedAcount++;
                            selectedRows.Add(row);
                        }
                    }
                    if(selectedAcount > 0)
                    {
                        int successCount = 0;
                        int executeCount = 0;
                        foreach (DynamicObject row in selectedRows)
                        {
                            //应收单相关记录
                            long id = Convert.ToInt64(row["Fid"]);
                            string srcBillno = row["FSRCBILLNO"].ToString();
                            string sourceType = row["FSOURCETYPE"].ToString();
                            long srcBillId = Convert.ToInt64(row["FSRCBILLID"]);
                            string fAbstract = row["FABSTRACT"].ToString();
                            DateTime reportDate = Convert.ToDateTime(row["FReportDate"]);
                            DateTime businessDate = Convert.ToDateTime(row["FSRCDATE"]);
                            TimeSpan dif = reportDate - businessDate;
                            int interestDays = dif.Days;
                            if(sourceType == receivableType)
                            {
                                //查找应收单并对计息天数和应计利息取值
                                OQLFilter receiveAbleFilter = new OQLFilter
                                {
                                    new OQLFilterHeadEntityItem() { FilterString = string.Format("FID = {0}", srcBillId) }
                                };
                                DynamicObject[] receiveAble = BusinessDataServiceHelper.Load(Context, "AR_receivable", null, receiveAbleFilter);
                                int overDueDates = Convert.ToInt32(receiveAble[0]["F_PMAF_OVERDUEDATES"]);
                                decimal interestAmount = Convert.ToDecimal(receiveAble[0]["F_PMAF_INTERESTAMOUNT"]);
                                decimal currentWritteAmount = Convert.ToDecimal(row["FCURWRITTENOFFAMOUNTFOR"]);
                                if (fAbstract == "")
                                {
                                    if (interestDays > 0)
                                    {
                                        interestAmount += Convert.ToDecimal(interestDays * currentWritteAmount * interestRate);
                                        //更新计息天数和应计利息，并标记是否记息
                                        if(overDueDates < interestDays) //当前计息天数大于单据计息天数
                                        {
                                            string sqlStr = string.Format(@"/*dialect*/
                                                    UPDATE T_AR_RECEIVABLE SET F_PMAF_OVERDUEDATES={1} WHERE FID={0};
                                                    UPDATE T_AR_RECEIVABLE SET F_PMAF_INTERESTAMOUNT={2} WHERE FID={0};
                                                    ", srcBillId, interestDays, interestAmount);
                                            int result = DBUtils.Execute(Context, sqlStr);
                                            if (result == 2)
                                            {
                                                string sqlStr1 = string.Format(@"/*dialect*/
                                                    UPDATE T_AR_RECMACTHLOGENTRY SET FABSTRACT='已计息' WHERE FID={0};
                                                    ", id);
                                                executeCount += DBUtils.Execute(Context, sqlStr1);
                                                successCount++;
                                            }
                                        }
                                        else //当前计息天数小于单据计息天数
                                        {
                                            string sqlStr = string.Format(@"/*dialect*/
                                                    UPDATE T_AR_RECEIVABLE SET F_PMAF_INTERESTAMOUNT={1} WHERE FID={0};
                                                    ", srcBillId, interestAmount);
                                            int result = DBUtils.Execute(Context, sqlStr);
                                            if (result == 1)
                                            {
                                                string sqlStr1 = string.Format(@"/*dialect*/
                                                    UPDATE T_AR_RECMACTHLOGENTRY SET FABSTRACT='已计息' WHERE FID={0};
                                                    ", id);
                                                executeCount += DBUtils.Execute(Context, sqlStr1);
                                                successCount++;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        string sqlStr = string.Format(@"/*dialect*/
                                            UPDATE T_AR_RECMACTHLOGENTRY SET FABSTRACT='无需计息' WHERE FID={0};
                                            ", id);
                                        executeCount += DBUtils.Execute(Context, sqlStr);
                                    }
                                }
                            }
                            else if(sourceType == receiveReturnType || sourceType == costReceivableType)
                            {
                                string sqlStr = string.Format(@"/*dialect*/
                                    UPDATE T_AR_RECMACTHLOGENTRY SET FABSTRACT='无需计息' WHERE FID={0};
                                    ", id);
                                executeCount += DBUtils.Execute(Context, sqlStr);
                            }
                        }
                        if (executeCount > 0)
                        {
                            if (successCount > 0)
                            {
                                View.ShowMessage(string.Format("成功计息{0}条记录,成功标记{1}条记录。", successCount, executeCount));
                            }
                            else
                            {
                                View.ShowMessage(string.Format("成功标记{0}条记录。", executeCount));
                            }
                            View.UpdateView("FRecordEntry");
                        }
                    }
                    else
                    {
                        View.ShowWarnningMessage("请选择至少一行数据");
                        //View.ShowMessage(ResManager.LoadKDString("abc", "003192000038640", SubSystemType.FIN));
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
